import { Server } from 'socket.io';

export class SignalingServer {
  constructor(httpServer, mediaManager, streamManager, config) {
    this.mediaManager = mediaManager;
    this.streamManager = streamManager;
    this.config = config;
    this.rooms = new Map(); // roomId -> Set<socketId>
    this.transports = new Map(); // socketId -> transport
    this.consumers = new Map(); // socketId -> consumers[]
    
    // 创建 Socket.IO 服务器
    this.io = new Server(httpServer, this.config.socketIO);
    
    this.setupSocketHandlers();
    console.log('Signaling server initialized');
  }

  setupSocketHandlers() {
    this.io.on('connection', (socket) => {
      console.log(`Client connected: ${socket.id}`);

      // 加入房间
      socket.on('join-room', async (data, callback) => {
        try {
          const { roomId } = data;
          console.log(`Client ${socket.id} joining room: ${roomId}`);
          
          socket.join(roomId);
          
          // 初始化房间数据
          if (!this.rooms.has(roomId)) {
            this.rooms.set(roomId, {
              clients: new Set(),
              rtspUrl: null
            });
          }
          
          const room = this.rooms.get(roomId);
          room.clients.add(socket.id);
          
          // 发送 Router RTP Capabilities
          const rtpCapabilities = this.mediaManager.getRouterRtpCapabilities();
          
          callback({
            success: true,
            rtpCapabilities
          });
          
        } catch (error) {
          console.error('Error joining room:', error);
          callback({ success: false, error: error.message });
        }
      });

      // 创建 WebRTC Transport
      socket.on('create-transport', async (data, callback) => {
        try {
          const { direction } = data; // 'send' or 'recv'
          console.log(`Creating ${direction} transport for client: ${socket.id}`);
          
          const transport = await this.mediaManager.createWebRtcTransport();

          // 存储 transport
          const transportId = transport.id;
          this.transports.set(transportId, {
            transport,
            socketId: socket.id,
            direction
          });

          // 监听 transport 事件
          transport.on('dtlsstatechange', (dtlsState) => {
            console.log(`Transport ${transportId} DTLS state: ${dtlsState}`);
          });

          transport.on('close', () => {
            console.log(`Transport ${transportId} closed`);
            this.transports.delete(transportId);
          });

          callback({
            success: true,
            transportOptions: {
              id: transport.id,
              iceParameters: transport.iceParameters,
              iceCandidates: transport.iceCandidates,
              dtlsParameters: transport.dtlsParameters
            }
          });

        } catch (error) {
          console.error('Error creating transport:', error);
          callback({ success: false, error: error.message });
        }
      });

      // 连接 Transport
      socket.on('connect-transport', async (data, callback) => {
        try {
          const { transportId, dtlsParameters } = data;
          console.log(`Connecting transport: ${transportId}`);
          
          const transportData = this.transports.get(transportId);
          if (!transportData) {
            throw new Error('Transport not found');
          }

          await transportData.transport.connect({ dtlsParameters });
          
          callback({ success: true });

        } catch (error) {
          console.error('Error connecting transport:', error);
          callback({ success: false, error: error.message });
        }
      });

      // 开始 RTSP 流
      socket.on('start-rtsp-stream', async (data, callback) => {
        try {
          const { rtspUrl, roomId } = data;
          console.log(`Starting RTSP stream: ${rtspUrl} for room: ${roomId}`);

          // 使用StreamManager获取或创建流
          const result = await this.streamManager.getOrCreateStream(roomId, rtspUrl);

          // 更新房间信息
          if (this.rooms.has(roomId)) {
            this.rooms.get(roomId).rtspUrl = rtspUrl;
          }

          // 通知房间内的所有客户端
          this.io.to(roomId).emit('rtsp-stream-started', {
            videoProducerId: result.videoProducerId,
            audioProducerId: result.audioProducerId
          });

          callback({ success: true, ...result });

        } catch (error) {
          console.error('Error starting RTSP stream:', error);
          callback({ success: false, error: error.message });
        }
      });

      // 创建 Consumer (接收流)
      socket.on('consume', async (data, callback) => {
        try {
          const { transportId, producerId, rtpCapabilities, roomId } = data;
          console.log(`Creating consumer for producer: ${producerId} in room: ${roomId}`);

          const transportData = this.transports.get(transportId);
          if (!transportData) {
            throw new Error('Transport not found');
          }

          const transport = transportData.transport;

          // 从StreamManager获取Producer
          const producer = this.streamManager.getProducer(roomId, producerId);
          console.log("----------------------producer", producer);
          if (!producer) {
            throw new Error('Producer not found in room');
          }

          // 检查是否可以消费
          if (!this.mediaManager.getRouter().canConsume({ producerId, rtpCapabilities })) {
            throw new Error('Cannot consume this producer');
          }

          // 创建 Consumer
          const consumer = await transport.consume({
            producerId,
            rtpCapabilities,
            paused: false // 立即开始播放
          });

          // 新增: 刷新流的活跃时间
          const streamObj = this.streamManager.streams.get(roomId);
          if (streamObj && typeof streamObj.refreshConsumerTime === 'function') {
            streamObj.refreshConsumerTime();
          }

          // 存储 consumer
          this.consumers.set(consumer.id, {
            consumer,
            socketId: socket.id,
            transportId
          });

          // 监听 consumer 事件
          consumer.on('transportclose', () => {
            console.log(`Consumer ${consumer.id} transport closed`);
            this.consumers.delete(consumer.id);
          });

          consumer.on('producerclose', () => {
            console.log(`Consumer ${consumer.id} producer closed`);
            socket.emit('consumer-closed', { consumerId: consumer.id });
            this.consumers.delete(consumer.id);
          });

          callback({
            success: true,
            consumerId: consumer.id,
            producerId: producerId,
            kind: consumer.kind,
            rtpParameters: consumer.rtpParameters
          });

        } catch (error) {
          console.error('Error creating consumer:', error);
          callback({ success: false, error: error.message });
        }
      });

      // 恢复 Consumer
      socket.on('resume-consumer', async (data, callback) => {
        try {
          const { consumerId } = data;
          console.log(`Resuming consumer: ${consumerId}`);
          
          const consumerData = this.consumers.get(consumerId);
          if (!consumerData) {
            throw new Error('Consumer not found');
          }

          await consumerData.consumer.resume();
          
          callback({ success: true });

        } catch (error) {
          console.error('Error resuming consumer:', error);
          callback({ success: false, error: error.message });
        }
      });

      // 停止 RTSP 流
      socket.on('stop-rtsp-stream', async (data, callback) => {
        try {
          const { roomId } = data;
          console.log(`Stopping RTSP stream for room: ${roomId}`);

          // 停止指定房间的流
          const stopped = await this.streamManager.stopStream(roomId);

          if (stopped) {
            // 通知房间内的所有客户端
            this.io.to(roomId).emit('rtsp-stream-stopped');
            callback({ success: true });
          } else {
            callback({ success: true, message: 'Stream already stopped' });
          }

        } catch (error) {
          console.error('Error stopping RTSP stream:', error);
          callback({ success: false, error: error.message });
        }
      });

      // 客户端断开连接
      socket.on('disconnect', async () => {
        console.log(`Client disconnected: ${socket.id}`);
        // 清理该客户端的资源
        this.cleanupClientResources(socket.id);
        // 检查房间是否无人，若无人则关闭推流
        for (const [roomId, room] of this.rooms.entries()) {
          if (room.clients.size === 0) {
            console.log(`Room ${roomId} is empty, stopping stream.`);
            await this.streamManager.stopStream(roomId);
          }
        }
      });
    });
  }

  cleanupClientResources(socketId) {
    // 清理 transports
    for (const [transportId, transportData] of this.transports.entries()) {
      if (transportData.socketId === socketId) {
        transportData.transport.close();
        this.transports.delete(transportId);
      }
    }

    // 清理 consumers
    for (const [consumerId, consumerData] of this.consumers.entries()) {
      if (consumerData.socketId === socketId) {
        consumerData.consumer.close();
        this.consumers.delete(consumerId);
      }
    }

    // 从房间中移除客户端
    for (const [roomId, room] of this.rooms.entries()) {
      room.clients.delete(socketId);
      if (room.clients.size === 0) {
        this.rooms.delete(roomId);
      }
    }
  }

  // 获取活跃的生产者
  getActiveProducers() {
    return this.rtspHandler.getProducers();
  }
}
